<?php
/**
 * User: hjd-yao
 * Date: 2019/4/22
 * Time: 10:46
 */

namespace App\Http\Controllers\Shop;

use App\Exports\DataExport;
use App\Helpers\Search;
use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Models\Shop\OrderGoodsModel;
use App\Models\Shop\OrderModel;
use DC\UserCenter\Models\UserBaseModel;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class ShopOrderController extends BackendController
{

    /**
     * @title 订单列表(自营)
     * @param Request $request
     * @return View
     */
    public function orderList(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where('store_id',0)
            ->orderByRaw('case when `status`<0 then 100 else 1 end desc,status desc ')->orderBy('created_at','desc')
            ->paginate($this->getPerPageNum());

        return view('backend::shop.order.list',[
            'page_title'=>'订单列表',
            'list'=>$list,
            'search'=>$search
        ]);
    }

    /**
     * @title 待付款订单
     * @param Request $request
     * @return View
     */
    public function waitPayOrder(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where([
            ['store_id','=',0],
            ['status','=',0],
        ])->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::shop.order.list',[
            'page_title'=>'待付款订单',
            'list'=>$list,
            'status'=>0,
            'search'=>$search
        ]);
    }

    /**
     * @title 待发货订单
     * @param Request $request
     * @return View
     */
    public function waitSendOrder(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where([
            ['store_id','=',0],
            ['status','=',1],
        ])->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::shop.order.list',[
            'page_title'=>'待发货订单',
            'list'=>$list,
            'status'=>1,
            'search'=>$search
        ]);
    }

    /**
     * @title 待确认订单
     * @param Request $request
     * @return View
     */
    public function waitConfirmOrder(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where([
            ['store_id','=',0],
            ['status','=',2],
        ])->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::shop.order.list',[
            'page_title'=>'待确认订单',
            'list'=>$list,
            'status'=>2,
            'search'=>$search
        ]);
    }

    /**
     * @title 已完成订单
     * @param Request $request
     * @return View
     */
    public function completeOrder(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where([
            ['store_id','=',0],
            ['status','>=',3],
        ])->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::shop.order.list',[
            'page_title'=>'已完成订单',
            'list'=>$list,
            'status'=>3,
            'search'=>$search
        ]);
    }

    /**
     * @title 订单详情
     * @param $order_id
     * @return View
     */
    public function detail($order_id)
    {
        $info = OrderModel::find($order_id);
        return view('backend::shop.order.detail',[
            'page_title'=>'订单详情',
            'info'=>$info
        ]);
    }

    /**
     * @title 修改收货人信息
     * @param Request $request
     * @param $order_id
     * @return SelfResponse|View
     */
    public function editPostInfo(Request $request, $order_id)
    {
        if($request->isMethod('post')){
            $info = OrderModel::find($order_id);
            if(!$info||!in_array($info->status,[0,1])){
                return SelfResponse::error('修改的订单不存在或已发货');
            }
            $info->consignee = $request->post('consignee');
            $info->phone = $request->post('phone');
            $info->post_address = $request->post('post_address');
            $info->zip_code = $request->post('zip_code');
            if($info->save()){
                return SelfResponse::success('收货信息修改成功',['b_ShopOrder_detail',['order_id'=>$order_id]]);
            }
            return SelfResponse::error('收货信息修改失败,请稍后再试!');
        }else{
            $info = OrderModel::find($order_id);
            return view('backend::shop.order.edit_post',[
                'page_title'=>'修改收货信息',
                'info'=>$info
            ]);
        }
    }

    /**
     * @title 修改支付金额
     * @param Request $request
     * @param $order_id
     * @return SelfResponse|View
     */
    public function editPayMoney(Request $request, $order_id)
    {
        if($request->isMethod('post')){
            $info = OrderModel::find($order_id);
            if(!$info||$info->status!=0){
                return SelfResponse::error('修改的订单不存在或已支付');
            }
            $validatedData = $request->validate([
                'pay_price' => ['required','numeric'],
            ],[
                'required'=>':attribute不能为空',
                'numeric'=>':attribute只能为数值',
            ],[
                'pay_price'=>'支付金额',
            ]);
            $info->pay_price = abs($validatedData['pay_price']);
            if($info->save()){
                return SelfResponse::success('支付金额修改成功',['b_ShopOrder_detail',['order_id'=>$order_id]]);
            }
            return SelfResponse::error('支付金额修改失败,请稍后再试!');
        }else{
            $info = OrderModel::find($order_id);
            return view('backend::shop.order.edit_pay',[
                'page_title'=>'修改支付费用',
                'info'=>$info
            ]);
        }
    }

    /**
     * @title 确认发货
     * @param Request $request
     * @param $order_id
     * @return SelfResponse|View
     */
    public function deliverGoods(Request $request, $order_id)
    {
        $info = OrderModel::find($order_id);
        if($request->isMethod('post')){
            if(!$info||$info->status>2){
                return SelfResponse::error('修改的订单不存在或已发货');
            }
            $validatedData = $request->validate([
                'express_name' => ['required','text_rule'],
                'express_num' => ['required','alpha_num'],
            ],[
                'required'=>':attribute不能为空',
                'text_rule'=>':attribute存在不合法字符',
                'alpha_num'=>':attribute只能是字母或数字',
            ],[
                'express_num'=>'快递单号',
                'express_name'=>'快递名称',
            ]);
            $info->express_name =$validatedData['express_name'];
            $info->express_num =$validatedData['express_num'];
            $info->is_send =1;
            $info->status =2;
            if($info->save()){
                return SelfResponse::success('确认发货成功',['b_ShopOrder_detail',['order_id'=>$order_id]]);
            }
            return SelfResponse::error('确认发货失败,请稍后再试!');
        }else{
            return view('backend::shop.order.deliver_goods',[
                'page_title'=>'确认发货',
                'info'=>$info
            ]);
        }
    }

    /**
     * @title 打印订单
     * @param $order_id
     * @return View
     */
    public function printOrder($order_id)
    {
        $info = OrderModel::find($order_id);
        return view('backend::shop.order.print_order',[
            'page_title'=>'打印订单',
            'info'=>$info
        ]);
    }

    /**
     * @title 关闭订单
     * @param Request $request
     * @return SelfResponse
     */
    public function close(Request $request)
    {
        $ids = $request->input('order_id');
        $ids = array_filter(is_array($ids)?$ids:str2arr($ids));
        if(!$ids){
            return SelfResponse::error('请选择要操作的数据');
        }

        if(OrderModel::whereIn('order_id',$ids)->update(['status'=>-1])){
            return SelfResponse::success('订单关闭成功','b_ShopOrder_orderList');
        }
        return SelfResponse::error('订单关闭失败');
    }

    /**
     * @title 删除订单
     * @param Request $request
     * @return SelfResponse
     */
    public function delete(Request $request)
    {
        $ids = $request->input('order_id');
        $ids = array_filter(is_array($ids)?$ids:str2arr($ids));
        if(!$ids){
            return SelfResponse::error('请选择要操作的数据');
        }
        $order_ids = OrderModel::where('store_id',0)->whereIn('order_id',$ids)->pluck('order_id')->toArray();
        if(!$order_ids){
            return SelfResponse::error('选择要操作的数据不合法');
        }
        if(OrderModel::whereIn('order_id',$order_ids)->delete()){
            OrderGoodsModel::whereIn('order_id',$order_ids)->delete();
            return SelfResponse::success('订单删除成功','b_ShopOrder_orderList');
        }
        return SelfResponse::error('订单删除失败');
    }


    /**
     * @title 导出订单
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function exportOrder(Request $request)
    {
        $search = Search::make($request)->bindModel(OrderModel::with(['goods','user']))
            ->input('order_sn','订单编号')
            ->input('user','编号/姓名/手机号','',['field'=>'uid'])
            ->time('created_at','下单时间')->bindSearchData()
            ->relationModel(['user'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);
        $model = $search->where();
        $status=$request->get('status');
        $model->where('status',$status);
        $data = $model->select(['order_sn','uid','pay_price','consignee','phone','post_address','zip_code','order_id'])->get();

        return (new DataExport())->setHeadings('订单详情',['订单编号','会员编号','订单价格','收货人信息','收货人联系方式','收货地址','商品信息'])
            ->setFormats(['A'=>DataType::TYPE_STRING2])
            ->filterData($data,function ($data){
                foreach ($data as &$item){
                    $item->uid = $item->user->user_number.'['.$item->user->user_phone.']'.'['.$item->user->real_name.']';
                    $order_goods = '';
                    if(!empty($item->goods)){
                        foreach ($item->goods as $goods){
                            $order_goods .= $goods->goods_name;
                            if($goods->goods_spec){
                                $order_goods .= $goods->goods_name.':'.$goods->goods_spec;
                            }
                            $order_goods .='(数量'.$goods->number.")\r\n" ;
                        }
                    }
                    $item->zip_code = $order_goods;
                    unset($item->user,$item->goods,$item->order_id,$order_goods);
                }
                unset($item);
                return $data;
        })->download('order'.SelfEncrypt::createCode().'.xlsx');
    }
}